package ui.units {

	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.utils.getTimer;
	
	import globals.Global;
	
	import ui.panel.PanelType;
	
	import util.GeomUtil;

	public class Tower extends BaseUnit {
		
		public var attackCD:uint;
		public var attackTime:uint;
		private var target:Monster;

		public function Tower() {
			super();
			
			attackTime = 0;
			buttonMode = true;
			
			addEventListener(MouseEvent.CLICK, clickHandler);
			addEventListener(MouseEvent.ROLL_OVER, overHandler);
			addEventListener(MouseEvent.ROLL_OUT, outHandler);
		}
		
		override public function init(bean:UnitBean):void {
			super.init(bean);
			view.scaleX = view.scaleY = 1.6;
			view.y = 10;
		}
		
		public function rotateTower(angle:Number):void {
			view.mc.head.rotation = angle;
		}
		
		public function attack():void {
			if (target != null 
				&& (Global.unitManager.getMonster(target.id) == null 
					|| !Global.unitManager.isMonsterInRange(x, y, bean.range, target)
					|| target.state == UnitState.DEAD)) {
				target = null;
			}
			if (target == null) {
				target = Global.unitManager.getMonsterByRange(x, y, bean.range);
			}
			if (target != null) {
				var bullerData:UnitBean = new UnitBean();
				bullerData.url = bean.bulletId;
				bullerData.id = "bullet1";
				var start:Point = new Point(x, y - 50);
				var end:Point = new Point(target.x, target.y);
				bullerData.x = start.x;
				bullerData.y = start.y;
				bullerData.start = start;
				bullerData.end = end;
				bullerData.damage = bean.damage;
				bullerData.speed = bean.speed;
				bullerData.attackRange = bean.attackRange;
				bullerData.target = target;
				Global.unitManager.fireBullet(bullerData, target);
				
				var angle:Number = GeomUtil.getAngle(target.x, target.y, x, y);
				rotateTower(angle);
			}
		}
		
		public function cast():void {
			Global.unitManager.addMagicTest(new Point(x, y), new Point());
		}
		
		private function clickHandler(event:Event):void {
//			Global.uiManager.showRange(x, y, 300);
			Global.uiManager.openPanel(PanelType.PRESENCE_PANEL);
		}
		
		private function overHandler(event:MouseEvent):void {
			Global.uiManager.showRange(x, y, bean.range);
		}
		
		private function outHandler(event:MouseEvent):void {
			Global.uiManager.hideRange();
		}
		
		override public function update():void {
			super.update();
			if (now - attackTime > bean.attackCD) {
				attack();
				attackTime = now;
			}
		}
	}
}